﻿using System;
using System.Linq;
using System.Threading.Tasks;
using HengTong.Model.Db.Hr;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.EntityFrameworkCore;

namespace HengTong.ViewModel.Hr.SysHrRenewRequestBillVms;

public partial class SysHrRenewRequestBillBatchVm
{
    /// <summary>
    /// 批量删除合同续签申请单
    /// </summary>
    /// <returns></returns>
    public async Task<bool> DoBatchDeleteAsync()
    {
        if (Ids == null || !Ids.Any())
        {
            MSD.AddModelError(" ", "请选择要删除的合同续签申请单");
            return false;
        }

        var transaction = await DC.Database.BeginTransactionAsync();
        try
        {
            // 将string ID转换为Guid列表
            var ids = Ids.Select(x => Guid.Parse(x)).ToList();

            // 先删除合同附件
            await DC.Set<SysHrRenewContractFile>()
                .Where(f => ids.Contains((Guid)f.HrRenewRequestBillId))
                .ExecuteDeleteAsync();

            // 删除主表数据
            await DC.Set<SysHrRenewRequestBill>()
                .Where(b => ids.Contains(b.ID))
                .ExecuteDeleteAsync();

            await DC.SaveChangesAsync();
            await transaction.CommitAsync();
            return true;
        }
        catch (Exception e)
        {
            await transaction.RollbackAsync();
            MSD.AddModelError(" ", $"批量删除异常：{e.Message}");
            return false;
        }
        finally
        {
            await transaction.DisposeAsync();
        }
    }
}